#include "pyconnector.h"

#include <QDebug>

PyConnector::PyConnector()
{
    Py_SetPythonHome(L"D:\\Python3.10");
    Py_Initialize();
    if (!Py_IsInitialized()) {
        qDebug() << "[ERROR] PY Initialize Failed";
    }
    QString chdir_cmd = "sys.path.append('./')";
    PyRun_SimpleString("import sys");
    PyRun_SimpleString(chdir_cmd.toStdString().c_str());
}

PyObject *PyConnector::PyLoadModFunction(const char *moduleName, const char *functionName)
{
    //加载模块
    PyObject *pModule = PyImport_ImportModule(moduleName);
    if (!pModule) { // 加载模块失败
        qDebug() << "[ERROR] Python get module failed.";
        return nullptr;
    }
    qDebug() << "[INFO] Python get module succeed.";
    //加载函数
    PyObject *pFunc = PyObject_GetAttrString(pModule, functionName);
    // 验证是否加载成功
    if (!pFunc || !PyCallable_Check(pFunc)) {
        qDebug() << "[ERROR] Can't find function";
        return nullptr;
    }
    qDebug() << "[INFO] Get function succeed.";
    return pFunc;
}

PyObject *PyConnector::PyCallFunction(PyObject *pFunc, PyObject *pPara)
{
    PyObject *pRet = PyObject_CallObject(pFunc, pPara);
    if (!pRet) {
        qDebug() << "[ERROR] Function Executed Failed!";
    }
    return pRet;
}

PyConnector::~PyConnector()
{
    Py_Finalize();
}

PyConnector *PyConnector::GetInstance()
{
    static PyConnector instance;
    return &instance;
}
